/**
 * 归一化2： 时间格式化
 * @param {number} time
 * @param {string} format 支持字符串，函数
 * @param {string} separator 分隔符
 * @param {boolean} isPad 是否补零
 * @returns {string} 格式化后的时间
 */

function formatTime(time, format, separator = "-", isPad = true) {
  const date = new Date(time);
  const dateInfo = {
    year: date.getFullYear() + "",
    month: date.getMonth() + 1,
    day: date.getDate(),
    hour: date.getHours(),
    minute: date.getMinutes(),
    second: date.getSeconds(),
  };

  console.log(dateInfo);
  if (isPad) {
    dateInfo.month =
      dateInfo.month < 10 ? "0" + dateInfo.month : dateInfo.month;
    dateInfo.day = dateInfo.day < 10 ? "0" + dateInfo.day : dateInfo.day;
    dateInfo.hour = dateInfo.hour < 10 ? "0" + dateInfo.hour : dateInfo.hour;
    dateInfo.minute =
      dateInfo.minute < 10 ? "0" + dateInfo.minute : dateInfo.minute;
    dateInfo.second =
      dateInfo.second < 10 ? "0" + dateInfo.second : dateInfo.second;
    dateInfo.month =
      dateInfo.month < 10 ? "0" + dateInfo.month : dateInfo.month;
    dateInfo.year = dateInfo.year.padStart(4, "0");
  }
  const formatFn = formatParam(format, separator);
  return formatFn(dateInfo);
}

// 辅助方法处理参数并返回处理替换方法
function formatParam(format, separator) {
  let timestr = "";
  if (typeof format === "function") {
    return format;
  }
  if (format == "date") {
    timestr = `yyyy${separator}MM${separator}dd`;
  }
  if (format == "datetime") {
    timestr = `yyyy${separator}MM${separator}dd HH:mm:ss`;
  }
  if (format === "month") {
    timestr = `yyyy${separator}MM`;
  }
  if (format === "time") {
    timestr = `HH:mm:ss`;
  }
  if (format === "year") {
    timestr = `yyyy`;
  }
  if (format === "yyyymmddhhmm") {
    timestr = `yyyy${separator}MM${separator}dd HH:mm`;
  }
  return (dateInfo) => {
    // 统一处理
    return (timestr = timestr
      .replace("yyyy", dateInfo.year)
      .replace("MM", dateInfo.month)
      .replace("dd", dateInfo.day)
      .replace("HH", dateInfo.hour)
      .replace("mm", dateInfo.minute));
  };
}

console.log(formatTime(1666400000000, "date", "/", true));
console.log(formatTime(1666400000000, "datetime", "/", true));
console.log(formatTime(1666400000000, "month", "/", true));
console.log(formatTime(1666400000000, "time", "/", true));
console.log(formatTime(1666400000000, "year", "/", true));
console.log(formatTime(1666400000000, "yyyymmddhhmm", "/", true));
console.log(formatTime(1666400000000, (dateInfo) => `${dateInfo.year}年`));
console.log(
  formatTime(
    1666400000000,
    (dateInfo) => `${dateInfo.year}年${dateInfo.month}月`
  )
);
